package www.sharetime.weshare.base;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;

import java.io.Serializable;

import butterknife.Unbinder;


/**
 * Fragment基础类
 */

@SuppressWarnings("WeakerAccess")
public abstract class BaseFragment extends Fragment {
    protected View mRoot;
    protected Bundle mBundle;
    private RequestManager mImgLoader;

    protected Unbinder unbind;

    protected LayoutInflater mInflater;

    private Context mContext;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBundle = getArguments();
        initBundle(mBundle);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        this.mInflater = inflater;
        mRoot = initView();
        initData();
        return mRoot;
    }


    public abstract View initView();

    protected View inflateView(int resId) {
        return this.mInflater.inflate(resId, null);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (unbind != null){
            unbind.unbind();
        }

        RequestManager manager = mImgLoader;
        if (manager != null)
            manager.onDestroy();
        mBundle = null;
    }

    protected abstract int getLayoutId();

    protected void initBundle(Bundle bundle) {

    }

    protected void initData() {

    }


    protected <T extends Serializable> T getBundleSerializable(String key) {
        if (mBundle == null) {
            return null;
        }
        return (T) mBundle.getSerializable(key);
    }

    /**
     * 获取一个图片加载管理器
     *
     * @return RequestManager
     */
    public synchronized RequestManager getImgLoader() {
        if (mImgLoader == null)
            mImgLoader = Glide.with(this);
        return mImgLoader;
    }

}
